package com.ruoyi.xuexiao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.constant.DataConstant;
import com.ruoyi.constant.v3.RwZtV3Enum;

import com.ruoyi.xuexiao.domain.entity.BasicRegion;
import com.ruoyi.xuexiao.domain.entity.RwTzV3;
import com.ruoyi.xuexiao.domain.param.SuperviseParam;
import com.ruoyi.xuexiao.domain.param.RwTzV3VParam;
import com.ruoyi.xuexiao.mapper.BasicRegionMapper;
import com.ruoyi.xuexiao.mapper.RwTzV3Mapper;
import com.ruoyi.xuexiao.service.AnalysisService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 统计分析
 * @author 田江余
 */
@Service
@AllArgsConstructor
public class AnalysisServiceImpl extends ServiceImpl<RwTzV3Mapper, RwTzV3> implements AnalysisService {

    private RwTzV3Mapper rwTzV3Mapper;

    private BasicRegionMapper basicRegionMapper;


    /**
     * 上半年市级核查任务进度
     * @author 田江余
     */
    @Override
    public List<RwTzV3VParam> inTheSecondHalfOfTheYear(ArrayList<RwTzV3VParam> rwTzV3DTOS, SuperviseParam supervise) {

        LambdaQueryWrapper<RwTzV3> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //上下半年，1,2
        lambdaQueryWrapper.eq(RwTzV3::getSxbn, supervise.getYear());
        //1是省，2是市，3是县
        if (supervise.getAdministration() > 0 && supervise.getAdministration() < 3) {
            // 如果administration的值在1到3之间，查询对应级别的数据
            lambdaQueryWrapper.eq(RwTzV3::getRwjb, supervise.getAdministration());
        }
        Long sl = rwTzV3Mapper.selectCount(lambdaQueryWrapper);

        // 已填报
        LambdaQueryWrapper<RwTzV3> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(RwTzV3::getRwzt, RwZtV3Enum.getCodes());
        // 查询已填报的任务列表
        List<RwTzV3> rwTzV3s = rwTzV3Mapper.selectList(wrapper);
        // 创建一个新的列表来存储查询结果
        List<RwTzV3VParam> resultDTOs = new ArrayList<>();
        // 用于存储每个市的任务数量和填报数量
        Map<String, RwTzV3VParam> cityTaskAndSubmissionCountMap = new HashMap<>();
        for (RwTzV3 rwTzV3 : rwTzV3s) {
            if (supervise.getAdministration() == 2 || supervise.getAdministration() == 1 || supervise.getAdministration() == 0) {
                String sjcs = basicRegionMapper.selectOne(
                        new LambdaQueryWrapper<BasicRegion>()
                                .eq(BasicRegion::getAdcd, rwTzV3.getSxzqdm())
                ).getAdnm();
                // 检查市名称是否已经存在于结果列表中
                if (!cityTaskAndSubmissionCountMap.containsKey(sjcs)) {
                    // 创建一个新的RwTzV3DTO对象来存储当前市的信息
                    RwTzV3VParam rwTzV3DTO = new RwTzV3VParam();
                    // 填报数量
                    rwTzV3DTO.setYtb(rwTzV3DTOS.size());
                    // 任务数量
                    rwTzV3DTO.setTotalRwsl(sl);
                    // 市名称
                    rwTzV3DTO.setSjcs(sjcs);
                    // 将当前市的信息添加到结果列表中
                    resultDTOs.add(rwTzV3DTO);
                    // 将市名称添加到map中
                    cityTaskAndSubmissionCountMap.put(sjcs, rwTzV3DTO);
                }
                // 增加任务数量和填报数量
                RwTzV3VParam cityInfo = cityTaskAndSubmissionCountMap.get(sjcs);
                cityInfo.setTotalRwsl(cityInfo.getTotalRwsl() + 1);
                cityInfo.setYtb(cityInfo.getYtb() + 1);
            }
            if (supervise.getAdministration() == 3) {
                List<BasicRegion> basicRegions = basicRegionMapper.selectList(
                        new LambdaQueryWrapper<BasicRegion>()
                                .eq(BasicRegion::getAdcd, rwTzV3.getXxzqdm())
                );
                for (BasicRegion basicRegion : basicRegions) {
                    // 检查市名称是否已经存在于结果列表中
                    if (!cityTaskAndSubmissionCountMap.containsKey(basicRegions)) {
                        // 创建一个新的RwTzV3DTO对象来存储当前市的信息
                        RwTzV3VParam rwTzV3DTO = new RwTzV3VParam();
                        // 填报数量
                        rwTzV3DTO.setYtb(rwTzV3DTOS.size());
                        // 任务数量
                        rwTzV3DTO.setTotalRwsl(sl);
                        // 市名称
                        rwTzV3DTO.setSjcs(basicRegion.getAdnm());
                        // 将当前市的信息添加到结果列表中
                        resultDTOs.add(rwTzV3DTO);
                        // 将县名称添加到map中
                        cityTaskAndSubmissionCountMap.put(basicRegion.getAdnm(), rwTzV3DTO);
                    }
                    // 增加任务数量和填报数量
                    RwTzV3VParam cityInfo = cityTaskAndSubmissionCountMap.get(basicRegion.getAdnm());
                    cityInfo.setTotalRwsl(cityInfo.getTotalRwsl() + 1);
                    cityInfo.setYtb(cityInfo.getYtb() + 1);
                }
            }
            }
        resultDTOs = resultDTOs.stream()
                .distinct()
                .collect(Collectors.toList());
            // 返回查询结果列表
            return resultDTOs;
        }


    /**
     * 上/下半年常规任务审核进度
     * @author 田江余
     */
    @Override
    public List<RwTzV3VParam> inTheSecondHalfOf(ArrayList<RwTzV3VParam> rwTzV3DTOS, SuperviseParam supervise) {
        // 任务数量
        LambdaQueryWrapper<RwTzV3> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        //上下半年，1,2
        lambdaQueryWrapper.eq(RwTzV3::getSxbn, supervise.getYear());
        //1是省，2是市，3是县
        if (supervise.getAdministration() > 0 && supervise.getAdministration() < 3) {            // 如果administration的值在1到3之间，查询对应级别的数据
            lambdaQueryWrapper.eq(RwTzV3::getRwjb, supervise.getAdministration());
        }
        Long sl = rwTzV3Mapper.selectCount(lambdaQueryWrapper);

        // 已填报
        LambdaQueryWrapper<RwTzV3> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(RwTzV3::getRwzt, RwZtV3Enum.getAi());
        // 查询已填报的任务列表
        List<RwTzV3> rwTzV3s = rwTzV3Mapper.selectList(wrapper);
        // 创建一个新的列表来存储查询结果
        List<RwTzV3VParam> resultDTOs = new ArrayList<>();
        // 用于存储每个市的任务数量和填报数量
        Map<String, RwTzV3VParam> cityTaskAndSubmissionCountMap = new HashMap<>();
        for (RwTzV3 rwTzV3 : rwTzV3s) {
            if (supervise.getAdministration() == 2 || supervise.getAdministration() == 1 || supervise.getAdministration() == 0) {
                String sjcs = basicRegionMapper.selectOne(
                        new LambdaQueryWrapper<BasicRegion>()
                                .eq(BasicRegion::getAdcd, rwTzV3.getSxzqdm())
                ).getAdnm();
                // 检查市名称是否已经存在于结果列表中
                if (!cityTaskAndSubmissionCountMap.containsKey(sjcs)) {
                    // 创建一个新的RwTzV3DTO对象来存储当前市的信息
                    RwTzV3VParam rwTzV3DTO = new RwTzV3VParam();
                    // 填报数量
                    rwTzV3DTO.setYtb(rwTzV3DTOS.size());
                    // 任务数量
                    rwTzV3DTO.setTotalRwsl(sl);
                    // 市名称
                    rwTzV3DTO.setSjcs(sjcs);
                    // 将当前市的信息添加到结果列表中
                    resultDTOs.add(rwTzV3DTO);
                    // 将市名称添加到map中
                    cityTaskAndSubmissionCountMap.put(sjcs, rwTzV3DTO);
                }
                // 增加任务数量和填报数量
                RwTzV3VParam cityInfo = cityTaskAndSubmissionCountMap.get(sjcs);
                cityInfo.setTotalRwsl(cityInfo.getTotalRwsl() + 1);
                cityInfo.setYtb(cityInfo.getYtb() + 1);
            }
            if (supervise.getAdministration() == 3) {
                List<BasicRegion> basicRegions = basicRegionMapper.selectList(
                        new LambdaQueryWrapper<BasicRegion>()
                                .eq(BasicRegion::getAdcd, rwTzV3.getXxzqdm())
                );
                for (BasicRegion basicRegion : basicRegions) {
                    // 检查市名称是否已经存在于结果列表中
                    if (!cityTaskAndSubmissionCountMap.containsKey(basicRegions)) {
                        // 创建一个新的RwTzV3DTO对象来存储当前市的信息
                        RwTzV3VParam rwTzV3DTO = new RwTzV3VParam();
                        // 填报数量
                        rwTzV3DTO.setYtb(rwTzV3DTOS.size());
                        // 任务数量
                        rwTzV3DTO.setTotalRwsl(sl);
                        // 市名称
                        rwTzV3DTO.setSjcs(basicRegion.getAdnm());
                        // 将当前市的信息添加到结果列表中
                        resultDTOs.add(rwTzV3DTO);
                        // 将县名称添加到map中
                        cityTaskAndSubmissionCountMap.put(basicRegion.getAdnm(), rwTzV3DTO);
                    }
                    // 增加任务数量和填报数量
                    RwTzV3VParam cityInfo = cityTaskAndSubmissionCountMap.get(basicRegion.getAdnm());
                    cityInfo.setTotalRwsl(cityInfo.getTotalRwsl() + 1);
                    cityInfo.setYtb(cityInfo.getYtb() + 1);
                }
            }
        }
        // 返回查询结果列表
        return resultDTOs;
    }

    /**
     * 常规任务填报进度(县级)
     * @author 田江余
     * @return
     */
    @Override
    public List<BasicRegion> getCountyRegionsByCityName(SuperviseParam supervise) {
        // 查询所有数据
        List<BasicRegion> basicRegionse = basicRegionMapper.selectList(null);
        // 过滤出所有市级行政区
        List<BasicRegion> cityRegions = basicRegionse.stream()
                .filter(r -> r.getLevel() == DataConstant.REGION_LEVEL_OF_CITY)
                .collect(Collectors.toList());
        // 为每个市级行政区设置其下一级的县级行政区列表
        List<BasicRegion> cityAndCountyRegions = cityRegions.stream()
                .map(city -> {
                    city.setChild(basicRegionse.stream()
                            .filter(r -> {
                                int i = r.getAdcd().length() - 2;
                                boolean f = (r.getAdcd().substring(0, i) + "00").equals(city.getAdcd());
                                return r.getLevel() == DataConstant.REGION_LEVEL_OF_COUNTY && f;
                            })
                            .collect(Collectors.toList()));
                    return city;
                })
                .collect(Collectors.toList());
        if (supervise.getCityName() != null) {
            cityAndCountyRegions = cityAndCountyRegions.stream()
                    .filter(e -> Objects.equals(e.getAdcd(), supervise.getCityName()))
                    .collect(Collectors.toList());
        }

        // 合并数据库查询
        Map<String, BasicRegion> cityRegionMap = cityRegions.stream()
                .collect(Collectors.toMap(BasicRegion::getAdcd, Function.identity()));
        // 批量查询县级行政区数量和特定状态的县级行政区数量
        List<RwTzV3> rwTzV3s = rwTzV3Mapper.selectList(new LambdaQueryWrapper<RwTzV3>()
                .eq(RwTzV3::getSxbn, supervise.getYear())
                .in(RwTzV3::getRwzt, RwZtV3Enum.getCodes()));


        // 统计数量
        Map<String, Long> rwTzV3CountMap = rwTzV3s.stream()
                .collect(Collectors.groupingBy(RwTzV3::getSxzqdm, Collectors.counting()));
        // 更新BasicRegions对象
        cityRegionMap.values().forEach(cityRegion -> {
            cityRegion.setTotalRwsl(rwTzV3CountMap.getOrDefault(cityRegion.getAdcd(), 0L));
            cityRegion.setYtb(rwTzV3CountMap.getOrDefault(cityRegion.getAdcd(), 0L));
        });
        // 确保child集合中的TotalRwsl和Ytb为null时返回0
        cityAndCountyRegions.forEach(cityRegion -> {
            if (cityRegion.getChild() != null) {
                cityRegion.getChild().forEach(childRegion -> {
                    if (childRegion.getTotalRwsl() == null) {
                        childRegion.setTotalRwsl(0L);
                    }
                    if (childRegion.getYtb() == null) {
                        childRegion.setYtb(0L);
                    }
                });
            }
        });
        return cityAndCountyRegions;
    }

    @Override
    public List<BasicRegion> regionsByCityName(SuperviseParam supervise) {
        // 查询所有数据
        List<BasicRegion> basicRegionse = basicRegionMapper.selectList(null);
        // 过滤出所有市级行政区
        List<BasicRegion> cityRegions = basicRegionse.stream()
                .filter(r -> r.getLevel() == DataConstant.REGION_LEVEL_OF_CITY)
                .collect(Collectors.toList());
        // 为每个市级行政区设置其下一级的县级行政区列表
        List<BasicRegion> cityAndCountyRegions = cityRegions.stream()
                .map(city -> {
                    city.setChild(basicRegionse.stream()
                            .filter(r -> {
                                int i = r.getAdcd().length() - 2;
                                boolean f = (r.getAdcd().substring(0, i) + "00").equals(city.getAdcd());
                                return r.getLevel() == DataConstant.REGION_LEVEL_OF_COUNTY && f;
                            })
                            .collect(Collectors.toList()));
                    return city;
                })
                .collect(Collectors.toList());
        if (supervise.getCityName()!=null){
            cityAndCountyRegions = cityAndCountyRegions.stream().filter(e-> Objects.equals(e.getAdcd(), supervise.getCityName())).collect(Collectors.toList());
        }
        // 合并数据库查询
        Map<String, BasicRegion> cityRegionMap = cityRegions.stream()
                .collect(Collectors.toMap(BasicRegion::getAdcd, Function.identity()));

        // 批量查询县级行政区数量和特定状态的县级行政区数量
        List<RwTzV3> rwTzV3s = rwTzV3Mapper.selectList(new LambdaQueryWrapper<RwTzV3>()
                .eq(RwTzV3::getSxbn,supervise.getYear())
                .in(RwTzV3::getRwzt, RwZtV3Enum.getAi()));

        // 统计数量
        Map<String, Long> rwTzV3CountMap = rwTzV3s.stream()
                .collect(Collectors.groupingBy(RwTzV3::getSxzqdm, Collectors.counting()));

        // 更新BasicRegions对象
        cityRegionMap.values().forEach(cityRegion -> {
            cityRegion.setTotalRwsl(rwTzV3CountMap.getOrDefault(cityRegion.getAdcd(), 0L));
            cityRegion.setYtb(rwTzV3CountMap.getOrDefault(cityRegion.getAdcd(), 0L));
        });
        // 确保child集合中的TotalRwsl和Ytb为null时返回0
        cityAndCountyRegions.forEach(cityRegion -> {
            if (!cityRegion.getChild().isEmpty()) {
                cityRegion.getChild().forEach(childRegion -> {
                    if (childRegion.getTotalRwsl() == null) {
                        childRegion.setTotalRwsl(0L);
                    }
                    if (childRegion.getYtb() == null) {
                        childRegion.setYtb(0L);
                    }
                });
            }
        });
        return cityAndCountyRegions;
    }

    /**
     * 任务类型统计(市级)
     * @author 田江余
     * @return
     */
    @Override
    public List<BasicRegion> countyRegionsByCityName(SuperviseParam supervise) {
        // 查询所有数据
        List<BasicRegion> basicRegionse = basicRegionMapper.selectList(null);
        // 过滤出所有市级行政区
        List<BasicRegion> cityRegions = basicRegionse.stream()
                .filter(r -> r.getLevel() == DataConstant.REGION_LEVEL_OF_CITY)
                .collect(Collectors.toList());
        for (BasicRegion cityRegion : cityRegions) {
            LambdaQueryWrapper<RwTzV3> wrapper = new LambdaQueryWrapper<>();
            //根据行政区的市行政区代码查询任务台账表的市行政区代码
            wrapper.eq(RwTzV3::getSxzqdm,cityRegion.getAdcd());
            //查询上下半年
            wrapper.eq(RwTzV3::getSxbn,supervise.getYear());
            List<RwTzV3> rwTzV3s = rwTzV3Mapper.selectList(wrapper);
            //提取任务来源123的数据
            cityRegion.setRwslx(rwTzV3s.stream()
                    .filter(p -> p.getRwly() == 1)
                    .count());
            cityRegion.setRwsljc(rwTzV3s.stream()
                    .filter(p -> p.getRwly() == 2)
                    .count());
            cityRegion.setRwslcg(rwTzV3s.stream()
                    .filter(p -> p.getRwly() == 3)
                    .count());
            // 如果查询到的数据为null或空，则设置属性为0
            if (rwTzV3s.isEmpty()) {
                cityRegion.setRwslx(0L);
                cityRegion.setRwsljc(0L);
                cityRegion.setRwslcg(0L);
            }
        }
        return cityRegions;
    }

    @Override
    public List<BasicRegion> countyRegionsBy(SuperviseParam supervise) {
        // 查询所有数据
        List<BasicRegion> basicRegionse = basicRegionMapper.selectList(null);
        // 过滤出所有市级行政区
        List<BasicRegion> cityRegions = basicRegionse.stream()
                .filter(r -> r.getLevel() == DataConstant.REGION_LEVEL_OF_CITY)
                .collect(Collectors.toList());
        // 为每个市级行政区设置其下一级的县级行政区列表
        List<BasicRegion> cityAndCountyRegions = cityRegions.stream()
                .map(city -> {
                    List<BasicRegion> child = basicRegionse.stream()
                            .filter(r -> {
                                int i = r.getAdcd().length() - 2;
                                boolean f = (r.getAdcd().substring(0, i) + "00").equals(city.getAdcd());
                                return r.getLevel() == DataConstant.REGION_LEVEL_OF_COUNTY && f;
                            })
                            .collect(Collectors.toList());
                    city.setChild(child);
                    return city;
                })
                .collect(Collectors.toList());
        for (BasicRegion cityRegion : cityAndCountyRegions) {
            LambdaQueryWrapper<RwTzV3> wrapper = new LambdaQueryWrapper<>();
            // 根据行政区的市行政区代码查询任务台账表的市行政区代码
            wrapper.eq(RwTzV3::getSxzqdm, cityRegion.getAdcd());
            // 查询上下半年
            wrapper.eq(RwTzV3::getSxbn, supervise.getYear());
            List<RwTzV3> rwTzV3s = rwTzV3Mapper.selectList(wrapper);
            // 提取任务来源123的数据
            cityRegion.setRwslx(rwTzV3s.stream()
                    .filter(p -> p.getRwly() == 1)
                    .count());
            cityRegion.setRwsljc(rwTzV3s.stream()
                    .filter(p -> p.getRwly() == 2)
                    .count());
            cityRegion.setRwslcg(rwTzV3s.stream()
                    .filter(p -> p.getRwly() == 3)
                    .count());

            // 如果查询到的数据为null或空，则设置属性为0
            if (rwTzV3s.isEmpty()) {
                cityRegion.setRwslx(0L);
                cityRegion.setRwsljc(0L);
                cityRegion.setRwslcg(0L);
            }

            // 确保child集合中的rwsljc，rwslx和rwslcg为null时返回0
            if (cityRegion.getChild() != null) {
                cityRegion.getChild().forEach(childRegion -> {
                    if (childRegion.getRwsljc() == null) {
                        childRegion.setRwsljc(0L);
                    }
                    if (childRegion.getRwslx() == null) {
                        childRegion.setRwslx(0L);
                    }
                    if (childRegion.getRwslcg() == null) {
                        childRegion.setRwslcg(0L);
                    }
                });
            }
        }
        if (supervise.getCityName() != null) {
            cityAndCountyRegions = cityAndCountyRegions.stream()
                    .filter(e -> Objects.equals(e.getAdcd(), supervise.getCityName()))
                    .collect(Collectors.toList());
        }
        return cityAndCountyRegions;
    }

    @Override
    public List<BasicRegion> getXzqBy() {
        // 查询所有数据
        List<BasicRegion> basicRegionse = basicRegionMapper.selectList(null);
        // 过滤出所有市级行政区
        List<BasicRegion> cityRegions = basicRegionse.stream()
                .filter(r -> r.getLevel() == DataConstant.REGION_LEVEL_OF_CITY)
                .collect(Collectors.toList());
        return cityRegions;
    }
    
    /**
     * 查询行政区县
     * @author 田江余
     * @return
     */
    @Override
    public List<BasicRegion> getXianBy() {
        // 查询所有数据
        List<BasicRegion> basicRegionse = basicRegionMapper.selectList(null);
        // 过滤出所有市级行政区
        List<BasicRegion> cityRegions = basicRegionse.stream()
                .filter(r -> r.getLevel() == DataConstant.REGION_LEVEL_OF_CITY)
                .collect(Collectors.toList());
        // 为每个市级行政区设置其下一级的县级行政区列表
        List<BasicRegion> cityAndCountyRegions = cityRegions.stream()
                .map(city -> {
                    city.setChild(basicRegionse.stream()
                            .filter(r -> {
                                int i = r.getAdcd().length() - 2;
                                boolean f = (r.getAdcd().substring(0, i) + "00").equals(city.getAdcd());
                                return r.getLevel() == DataConstant.REGION_LEVEL_OF_COUNTY && f;
                            })
                            .collect(Collectors.toList()));
                    return city;
                })
                .collect(Collectors.toList());
        return cityAndCountyRegions;
    }
    
}

